package com.demo.job.controller;

import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 熔断器监控控制器
 * 提供熔断器状态查询接口
 */
@Slf4j
@RestController
@RequestMapping("/api/monitor")
public class CircuitBreakerController {

    @Autowired
    private CircuitBreakerRegistry circuitBreakerRegistry;

    /**
     * 获取所有熔断器状态
     * @return 所有熔断器的状态信息
     */
    @GetMapping("/circuit-breakers")
    public Map<String, Object> getCircuitBreakersStatus() {
        Map<String, Object> result = new HashMap<>();
        
        circuitBreakerRegistry.getAllCircuitBreakers().forEach(circuitBreaker -> {
            Map<String, Object> status = new HashMap<>();
            status.put("state", circuitBreaker.getState().toString());
            status.put("metrics", getCircuitBreakerMetrics(circuitBreaker));
            result.put(circuitBreaker.getName(), status);
        });
        
        return result;
    }

    /**
     * 获取指定熔断器状态
     * @param name 熔断器名称
     * @return 指定熔断器的状态信息
     */
    @GetMapping("/circuit-breakers/{name}")
    public Map<String, Object> getCircuitBreakerStatus(@PathVariable String name) {
        try {
            CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker(name);
            Map<String, Object> result = new HashMap<>();
            result.put("name", name);
            result.put("state", circuitBreaker.getState().toString());
            result.put("metrics", getCircuitBreakerMetrics(circuitBreaker));
            return result;
        } catch (Exception e) {
            log.error("获取熔断器状态失败: {}", name, e);
            Map<String, Object> result = new HashMap<>();
            result.put("error", "熔断器不存在或获取状态失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 获取熔断器指标信息
     * @param circuitBreaker 熔断器实例
     * @return 指标信息
     */
    private Map<String, Object> getCircuitBreakerMetrics(CircuitBreaker circuitBreaker) {
        Map<String, Object> metrics = new HashMap<>();
        CircuitBreaker.Metrics cbMetrics = circuitBreaker.getMetrics();
        
        metrics.put("failureRate", cbMetrics.getFailureRate());
        metrics.put("numberOfBufferedCalls", cbMetrics.getNumberOfBufferedCalls());
        metrics.put("numberOfFailedCalls", cbMetrics.getNumberOfFailedCalls());
        metrics.put("numberOfSuccessfulCalls", cbMetrics.getNumberOfSuccessfulCalls());
        metrics.put("numberOfNotPermittedCalls", cbMetrics.getNumberOfNotPermittedCalls());
        
        return metrics;
    }
}